package com.packet.cheng.util;

import cn.hutool.core.util.RandomUtil;

import java.math.BigDecimal;

/**
 * @author 张在成
 */
public class RedPacketAlogrom {

    /**
     * 二倍均值法
     * @param totalMoney
     * @param redPacketCount
     * @return
     */
    public  static  void  divideRedPacket(BigDecimal totalMoney,int redPacketCount){

        if ((totalMoney.compareTo(BigDecimal.valueOf(0.01))<0 || redPacketCount<0)){
            return;
        }
        //抢红包
        //剩余总金额
        BigDecimal  balance=totalMoney;
        //剩余红包个数
        int baCount=redPacketCount;
        System.out.println(baCount);
        System.out.println("====================抢红包开始===================");
        //定义变量,验证总金额
        BigDecimal totalValidate=BigDecimal.valueOf(0);

        for (int i=0;i<redPacketCount-1;i++){

            //随机抢到的金额
            //最少抢到的金额
            BigDecimal  min=BigDecimal.valueOf(0.01);
            BigDecimal result=balance.divide(BigDecimal.valueOf(baCount),2,BigDecimal.ROUND_HALF_DOWN);
            //二倍均值法
            result=result.multiply(BigDecimal.valueOf(2));
            //将金钱单位由元转成分
            int limit=(int)(result.doubleValue()*100);
            //随机抢到的金额
            BigDecimal randomAmmount=BigDecimal.valueOf(RandomUtil.randomInt(limit-1)+1).divide(BigDecimal.valueOf(100),2,BigDecimal.ROUND_HALF_DOWN);

            //更新剩余总金额：抢到的总金额减-随机金额
            balance=balance.subtract(randomAmmount);

            //更新红包剩余个数
            baCount--;

            //抢到的金额累加
            totalValidate=totalValidate.add(randomAmmount);

            System.out.println("第"+(i+1)+"个人抢到的红包金额为："+randomAmmount+"元，红包余额为"+balance+"元");

        }

        System.out.println("第"+redPacketCount+"个人抢到的红包金额："+balance+"元，红包余额为0元");

        //累计金额
        totalValidate=totalValidate.add(balance);

        System.out.println("验证红包发出的总金额："+totalValidate+"元");

        System.out.println("====================抢红包结束===================");

    }

    public static void main(String[] args) {

        
        divideRedPacket(BigDecimal.valueOf(20),5);

    }
}
